package com.zj.easytotwitter;

import android.app.Activity;
import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class MyActivity extends Activity implements View.OnClickListener{

    private File[] files;
    private List<String> paths = new ArrayList<String>();
    private final static String FILENAME="/sdcard/Test/";
    private ImageView image;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        image =(ImageView)findViewById(R.id.image);
        String path=Environment.getExternalStorageDirectory().getAbsolutePath();
        
        // 遍历 SD 卡下 .png 文件通过微信分享，保证SD卡根目录下有.png的文件
//        File root = Environment.getExternalStorageDirectory();
        	File root = new File(path+"/sdcard/");
        
//        File destDir = new File(FILENAME); if (!destDir.exists()) { destDir.mkdirs();  } 
        
        	Bitmap abitmap = new BitmapFactory().decodeResource(getResources(), R.drawable.header_default);
        	Bitmap bbitmap = new BitmapFactory().decodeResource(getResources(), R.drawable.header_default);
        	image.setImageBitmap(abitmap);
        	File b = new File(path+"/sdcard/");
			if(!b.exists()){
				b.mkdirs();
			}
        	
        	 try {
				File a = new File(path+"/sdcard/", "a.png");
				File bmap = new File(path+"/sdcard/", "b.png");
				 if (!a.exists()) {
					 a.createNewFile();
				 }
				 if(!b.exists()){
					 bmap.createNewFile();
				 }
				 FileOutputStream out = new FileOutputStream(a);
				 FileOutputStream bout = new FileOutputStream(bmap);
				 abitmap.compress(CompressFormat.PNG, 90, out);
				 abitmap.compress(CompressFormat.PNG, 90, bout);
				 out.flush();
				 out.close();
				 bout.flush();
				 bout.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        
        files = root.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
            	Toast.makeText(MyActivity.this, pathname.getName(), 1).show();
                if (pathname.getName().endsWith(".png"))
                    return true;
                return false;
            }
        });

        for(File file :files){
            //paths.add(file.getAbsolutePath());
        }

    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    ShareUtils.shareDraPicsToWXCircle(getApplicationContext(), "你好，成功的分享了多张照片到微信",filess);
                    break;
                case 1:
                    image.setImageBitmap(bitmap);
                    break;
                    default:
                        break;
            }
        }
    };

    private ArrayList<File> filess=new ArrayList<>();
    Bitmap bitmap;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.share_btn1:
                paths.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1524407449522&di=1f1d4454b442d3e882a15ecaf017f7c6&imgtype=0&src=http%3A%2F%2Fpic1.cxtuku.com%2F00%2F07%2F37%2Fb066ac396c08.jpg");
                paths.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1524407449522&di=1f1d4454b442d3e882a15ecaf017f7c6&imgtype=0&src=http%3A%2F%2Fpic1.cxtuku.com%2F00%2F07%2F37%2Fb066ac396c08.jpg");
                String url="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1524407449522&di=1f1d4454b442d3e882a15ecaf017f7c6&imgtype=0&src=http%3A%2F%2Fpic1.cxtuku.com%2F00%2F07%2F37%2Fb066ac396c08.jpg";
                ShareUtils.shareBitmapPicsToWXCircle(this, "你好，成功的分享了多张照片到微信",url);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //getBitmap("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1524407449522&di=1f1d4454b442d3e882a15ecaf017f7c6&imgtype=0&src=http%3A%2F%2Fpic1.cxtuku.com%2F00%2F07%2F37%2Fb066ac396c08.jpg");
                     //bitmap=GetLocalOrNetBitmap("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1524407449522&di=1f1d4454b442d3e882a15ecaf017f7c6&imgtype=0&src=http%3A%2F%2Fpic1.cxtuku.com%2F00%2F07%2F37%2Fb066ac396c08.jpg");
                        //handler.obtainMessage(1).sendToTarget();

                    }
                }).start();
                /*if (paths == null || paths.size() == 0) {
                    Toast.makeText(this, "SD卡根目录下无.png格式照片", Toast.LENGTH_SHORT).show();
                } else {

                    ShareUtils.share9PicsToWXCircle(this, "你好，成功的分享了多张照片到微信", paths);
                    //ShareUtils.shareDraPicsToWXCircle(this, "你好，成功的分享了多张照片到微信",filess);
                    *//*new Thread(new Runnable() {
                        @Override
                        public void run() {
                            uris.clear();
                            paths.clear();
                            for (int i=0;i<2;i++){
                                uris.add(getDraUris());
                            }
                            for (int i=0;i<uris.size();i++){
                                    filess.add(new File(uris.get(i).toString()));
                            }
                            handler.obtainMessage(0).sendToTarget();
                        }
                    }).start();*//*
                    break;
                }*/


        }


    }

    //获取本地drawble里面的图片的uri
    private ArrayList<Uri> uris=new ArrayList<>();
    private Uri getDraUris(){
        Uri uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
        + getResources().getResourcePackageName(R.drawable.header_default) + "/"
        + getResources().getResourceTypeName(R.drawable.header_default) + "/"
        + getResources().getResourceEntryName(R.drawable.header_default));
        return uri;
    }

    //网络地址转bitmap
    private Bitmap strToBitmap(){
        Bitmap bitmap=null;

        return bitmap;
    }

    public Bitmap getBitmap(String url) {
        Bitmap bm = null;
        try {
            URL iconUrl = new URL(url);
            URLConnection conn = iconUrl.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;

            int length = http.getContentLength();

            conn.connect();
            // 获得图像的字符流
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();// 关闭流
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("---bm","宽度："+bm.getWidth()+"高度："+bm.getHeight());
        return bm;
    }

    /**
     * 把网络资源图片转化成bitmap
     * @param url  网络资源图片
     * @return  Bitmap
     */
    public static Bitmap GetLocalOrNetBitmap(String url) {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedInputStream(new URL(url).openStream(), 1024);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, 1024);
            copy(in, out);
            out.flush();
            byte[] data = dataStream.toByteArray();
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            data = null;
            Log.e("---bm","宽度："+bitmap.getWidth()+"高度："+bitmap.getHeight());
            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static void copy(InputStream in, OutputStream out)
            throws IOException {
        byte[] b = new byte[1024];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }

}
